<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Search, Plus, Edit, Delete, Download, Refresh, View } from '@element-plus/icons-vue';

// 表格数据
const treatmentData = ref([
  {
    id: 'TR-2023001',
    name: '高血压综合控制方案',
    category: '慢病管理',
    targetGroup: '高血压患者',
    department: '内科',
    period: '3个月',
    visitFrequency: '每月1次',
    status: '启用',
    createdBy: '张医生',
    createdAt: '2023-05-15',
    updateAt: '2023-06-20'
  },
  {
    id: 'TR-2023002',
    name: '2型糖尿病管理方案',
    category: '慢病管理',
    targetGroup: '糖尿病患者',
    department: '内分泌科',
    period: '6个月',
    visitFrequency: '每月1次',
    status: '启用',
    createdBy: '李医生',
    createdAt: '2023-04-10',
    updateAt: '2023-06-18'
  },
  {
    id: 'TR-2023003',
    name: '骨科术后康复方案',
    category: '术后康复',
    targetGroup: '骨科手术患者',
    department: '骨科',
    period: '45天',
    visitFrequency: '每周1次',
    status: '启用',
    createdBy: '王医生',
    createdAt: '2023-05-22',
    updateAt: '2023-05-22'
  },
  {
    id: 'TR-2023004',
    name: '产后护理与康复方案',
    category: '妇幼保健',
    targetGroup: '产后女性',
    department: '妇产科',
    period: '42天',
    visitFrequency: '每周1次',
    status: '启用',
    createdBy: '陈医生',
    createdAt: '2023-06-01',
    updateAt: '2023-07-10'
  },
  {
    id: 'TR-2023005',
    name: '心肌梗塞康复方案',
    category: '心脏康复',
    targetGroup: '心梗患者',
    department: '心内科',
    period: '6个月',
    visitFrequency: '前3个月每周1次，后3个月每月1次',
    status: '启用',
    createdBy: '刘医生',
    createdAt: '2023-03-18',
    updateAt: '2023-07-05'
  },
  {
    id: 'TR-2023006',
    name: '儿童哮喘管理方案',
    category: '慢病管理',
    targetGroup: '哮喘儿童',
    department: '儿科',
    period: '12个月',
    visitFrequency: '每2个月1次',
    status: '启用',
    createdBy: '林医生',
    createdAt: '2023-04-25',
    updateAt: '2023-06-12'
  },
  {
    id: 'TR-2023007',
    name: '脑卒中康复计划',
    category: '神经康复',
    targetGroup: '脑卒中患者',
    department: '神经内科',
    period: '12个月',
    visitFrequency: '前3个月每周2次，后续每月1次',
    status: '草稿',
    createdBy: '赵医生',
    createdAt: '2023-07-01',
    updateAt: '2023-07-01'
  }
]);

// 搜索条件和过滤
const searchForm = reactive({
  keyword: '',
  department: '',
  category: '',
  status: ''
});

// 部门选项
const departmentOptions = [
  { value: '', label: '全部科室' },
  { value: '内科', label: '内科' },
  { value: '内分泌科', label: '内分泌科' },
  { value: '骨科', label: '骨科' },
  { value: '妇产科', label: '妇产科' },
  { value: '心内科', label: '心内科' },
  { value: '儿科', label: '儿科' },
  { value: '神经内科', label: '神经内科' }
];

// 分类选项
const categoryOptions = [
  { value: '', label: '全部分类' },
  { value: '慢病管理', label: '慢病管理' },
  { value: '术后康复', label: '术后康复' },
  { value: '妇幼保健', label: '妇幼保健' },
  { value: '心脏康复', label: '心脏康复' },
  { value: '神经康复', label: '神经康复' }
];

// 状态选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: '启用', label: '启用' },
  { value: '草稿', label: '草稿' },
  { value: '停用', label: '停用' }
];

// 搜索方法
const searchTreatments = () => {
  // 实际应用中应该调用API进行搜索
  console.log('搜索条件:', searchForm);
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.department = '';
  searchForm.category = '';
  searchForm.status = '';
  searchTreatments();
};

// 表格分页设置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: treatmentData.value.length
});

// 处理分页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
};

const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
};

// 过滤后的数据
const filteredTreatments = computed(() => {
  let result = [...treatmentData.value];
  
  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase();
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.id.toLowerCase().includes(keyword) ||
      item.targetGroup.toLowerCase().includes(keyword)
    );
  }
  
  // 科室过滤
  if (searchForm.department) {
    result = result.filter(item => item.department === searchForm.department);
  }
  
  // 分类过滤
  if (searchForm.category) {
    result = result.filter(item => item.category === searchForm.category);
  }
  
  // 状态过滤
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status);
  }
  
  // 更新总数
  pagination.total = result.length;
  
  return result;
});

// 处理查看
const handleView = (row) => {
  console.log('查看方案:', row);
  // 实际应用中跳转到详情页
};

// 处理编辑
const handleEdit = (row) => {
  console.log('编辑方案:', row);
  // 实际应用中打开编辑对话框或跳转到编辑页
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除诊疗方案"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中应该调用API删除数据
    treatmentData.value = treatmentData.value.filter(item => item.id !== row.id);
    ElMessage({
      type: 'success',
      message: '删除成功'
    });
  }).catch(() => {});
};

// 新建诊疗方案对话框
const dialogVisible = ref(false);
const treatmentForm = reactive({
  name: '',
  category: '',
  targetGroup: '',
  department: '',
  period: '',
  visitFrequency: '',
  description: '',
  status: '草稿'
});

// 处理新建
const handleAdd = () => {
  // 重置表单
  Object.keys(treatmentForm).forEach(key => {
    treatmentForm[key] = key === 'status' ? '草稿' : '';
  });
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  // 表单验证
  if (!treatmentForm.name || !treatmentForm.category || !treatmentForm.department) {
    ElMessage.warning('请填写必填项');
    return;
  }
  
  // 创建新记录
  const newTreatment = {
    id: `TR-${new Date().getFullYear()}${String(treatmentData.value.length + 1).padStart(3, '0')}`,
    ...treatmentForm,
    createdBy: '当前用户',
    createdAt: new Date().toISOString().split('T')[0],
    updateAt: new Date().toISOString().split('T')[0]
  };
  
  // 添加到列表
  treatmentData.value.unshift(newTreatment);
  
  // 关闭对话框
  dialogVisible.value = false;
  
  ElMessage({
    type: 'success',
    message: '创建成功'
  });
};

// 导出数据
const exportData = () => {
  ElMessage({
    type: 'info',
    message: '正在导出数据，请稍后...'
  });
  // 实际应用中应该调用API导出数据
};

// 刷新数据
const refreshData = () => {
  ElMessage({
    type: 'info',
    message: '正在刷新数据...'
  });
  // 实际应用中应该调用API刷新数据
};
</script>

<template>
  <div class="treatments-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="关键词">
              <el-input 
                v-model="searchForm.keyword" 
                placeholder="搜索方案名称/ID/适用对象" 
                clearable
                @keyup.enter="searchTreatments"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="科室">
              <el-select v-model="searchForm.department" placeholder="请选择科室" clearable style="width: 100%">
                <el-option 
                  v-for="item in departmentOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="分类">
              <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 100%">
                <el-option 
                  v-for="item in categoryOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option 
                  v-for="item in statusOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="searchTreatments" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left">
        <el-button type="primary" @click="handleAdd" :icon="Plus">新建诊疗方案</el-button>
      </div>
      <div class="right">
        <el-button @click="exportData" :icon="Download">导出</el-button>
        <el-button @click="refreshData" :icon="Refresh">刷新</el-button>
      </div>
    </div>
    
    <!-- 诊疗方案表格 -->
    <el-table :data="filteredTreatments" style="width: 100%" border stripe>
      <el-table-column prop="id" label="方案ID" min-width="120" />
      <el-table-column prop="name" label="方案名称" min-width="180" />
      <el-table-column prop="category" label="分类" min-width="120" />
      <el-table-column prop="targetGroup" label="适用对象" min-width="150" />
      <el-table-column prop="department" label="负责科室" min-width="120" />
      <el-table-column prop="period" label="周期" min-width="100" />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="scope">
          <el-tag 
            :type="scope.row.status === '启用' ? 'success' : scope.row.status === '停用' ? 'info' : 'warning'"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateAt" label="更新时间" min-width="120" />
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)" :icon="View">查看</el-button>
          <el-button size="small" type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      >
      </el-pagination>
    </div>
    
    <!-- 新建/编辑诊疗方案对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新建诊疗方案"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="treatmentForm" label-width="100px">
        <el-form-item label="方案名称" required>
          <el-input v-model="treatmentForm.name" placeholder="请输入方案名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" required>
              <el-select v-model="treatmentForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option 
                  v-for="item in categoryOptions.filter(item => item.value)" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责科室" required>
              <el-select v-model="treatmentForm.department" placeholder="请选择科室" style="width: 100%">
                <el-option 
                  v-for="item in departmentOptions.filter(item => item.value)" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="适用对象">
          <el-input v-model="treatmentForm.targetGroup" placeholder="请输入适用对象" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="方案周期">
              <el-input v-model="treatmentForm.period" placeholder="例如：3个月" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访频率">
              <el-input v-model="treatmentForm.visitFrequency" placeholder="例如：每月1次" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="方案描述">
          <el-input
            v-model="treatmentForm.description"
            type="textarea"
            rows="4"
            placeholder="请输入方案详细描述"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="treatmentForm.status">
            <el-radio label="草稿">草稿</el-radio>
            <el-radio label="启用">启用</el-radio>
            <el-radio label="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.treatments-container {
  width: 100%;
}

.search-container {
  background-color: var(--background-light);
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-form {
  width: 100%;
}

.search-buttons {
  margin-bottom: 0;
  display: flex;
  justify-content: center;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .table-toolbar {
    flex-direction: column;
    gap: 10px;
  }
  
  .left, .right {
    display: flex;
    gap: 10px;
  }
}
</style> 